<template>
  <div class="app-container">
    <el-main>
      <div class="search">
        <el-form ref="searchForm" size="mini" :inline="true" :model="searchForm" class="form-inline">
          <el-form-item label="名称：" prop="name">
            <el-input v-model.trim="searchForm.name" clearable placeholder="请输入名称"/>
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select v-model="searchForm.status" filterable clearable placeholder="请选择状态">
              <el-option label="启用" :value="1"/>
              <el-option label="禁用" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="searchSubmit('searchForm')">搜索</el-button>
            <el-button type="info" plain @click="searchReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-row :gutter="20" type="flex" align="center">
        <el-col>
          <el-button v-permission="'department_add_top'" type="primary" size="mini" @click.native="showAdd()">新增顶级
          </el-button>
          <!-- <el-button type="danger" size="small" :disabled="!selectIds.length>0" @click.native="delVer()">删除 </el-button>-->
        </el-col>
      </el-row>

      <el-table ref="multipleTable" v-loading="tabLoading" size="mini" stripe :data="tableData" tooltip-effect="dark"
                style="width: 100%"
                :row-class-name="tableRowClassName" border
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                default-expand-all highlight-current-row row-key="id" @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" align="center" width="55"></el-table-column> -->
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="100" show-overflow-tooltip/>
        <el-table-column prop="desp" label="职能描述" show-overflow-tooltip/>
        <el-table-column prop="head" label="抬头"></el-table-column>
        <el-table-column prop="sort" label="排序" width="80" show-overflow-tooltip sortable fixed="right"/>
        <el-table-column prop="status" label="启用" align="center" width="80" fixed="right">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" size="mini" v-permission-disabled="'department_switch'"
                       :active-value="1"
                       :inactive-value="0"
                       @change="changeStatus($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="accounting" label="独立核算" align="center" width="80" fixed="right">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.accounting" size="mini" v-permission-disabled="'department_switch'"
                       :active-value="true"
                       :inactive-value="false"
                       @change="changeAccounting($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation">
              <el-button v-permission="'department_add'" type="primary" icon="el-icon-edit-outline" size="mini"
                         @click.native="showAdd(scope.row)"
              >新增下级
              </el-button>
              <el-button v-permission="'department_edit'" type="primary" icon="el-icon-edit-outline" size="mini"
                         @click.native="showEdit(scope.row)"
              >编辑
              </el-button>
              <el-button v-permission="'department_del'" type="danger" icon="el-icon-delete" size="small"
                         @click.native="delVer(scope.row.id)"
              >删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <el-dialog :close-on-click-modal="false" :title="(cuForm.id?'编辑':'新增')" center :visible.sync="dialogCU"
               width="50%"
               @close="dialogCUClose('cuForm')"
    >
      <el-form ref="cuForm" v-loading="dialogCULoading" :rules="cuRules" :model="cuForm" label-width="130px" center>
        <el-row class="row-bg">
          <el-col :span="22">
            <el-form-item label="名称" prop="name">
              <el-col :span="24">
                <el-input v-model.trim="cuForm.name" clearable placeholder="请输入名称"/>
              </el-col>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-col :span="24">
                <el-radio-group v-model="cuForm.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
            <el-form-item label="独立核算" prop="accounting">
              <el-col :span="24">
                <el-radio-group v-model="cuForm.accounting">
                  <el-radio :label="true">启用</el-radio>
                  <el-radio :label="false">禁用</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
            <el-form-item v-if="cuForm.accounting" label="抬头" prop="head">
              <el-col :span="24">
                <el-input v-model="cuForm.head" placeholder="请输入公司抬头"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item v-if="cuForm.accounting" label="开户行" prop="bank">
              <el-col :span="24">
                <el-input v-model="cuForm.bank" placeholder="请输入开户行"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item v-if="cuForm.accounting" label="银行卡号" prop="bank_card_num">
              <el-col :span="24">
                <el-input v-model="cuForm.bank_card_num" placeholder="请输入银行卡号"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item v-if="cuForm.accounting" prop="contract_prefix">
              <template slot="label">
                <el-tooltip effect="dark" content="系统生成的合同编号前缀" placement="left">
                  <span>
                    <i class="el-icon-question"></i>合同编号前缀
                  </span>
                </el-tooltip>
              </template>
              <el-col :span="24">
                <el-input v-model="cuForm.contract_prefix" style="width: 200px" placeholder="请输入合同编号前缀"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="负责的业务" prop="business">
              <el-col :span="24">
                <el-select v-model="cuForm.business" clearable placeholder="请选择">
                  <el-option
                    value="sales"
                    label="销售"
                  />
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="职能描述" prop="desp">
              <el-col :span="24">
                <el-input v-model.trim="cuForm.desp" clearable type="textarea" :rows="4" maxlength="100" show-word-limit
                          placeholder="职能描述"
                />
              </el-col>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-col :span="24">
                <el-input v-model.trim="cuForm.sort" type="number" placeholder="请输入排序"/>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.native="dialogCU=false">取 消</el-button>
        <el-button type="primary" @click.native="onSubmit(cuForm.id)">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  list,
  add,
  edit,
  del,
  change_status,
  change_accounting
} from '@/api/system/department.js'
import {
  Message
} from 'element-ui'

export default {
  data() {
    return {
      // search form
      searchForm: {
        name: null,
        status: null
      },

      // list table
      tableData: [], // 列表数据
      selectIds: [], // 多选选项id

      listParams: {
        name: null,
        status: null
      }, // list参数
      tabLoading: true,
      // CU dialog
      dialogCULoading: false,
      dialogCU: false, // 增修弹框显示

      cuForm: {
        id: null,
        name: null,
        pid: 0,
        rid: 0,
        desp: null,
        status: 0,
        sort: 1,
        accounting: false,
        head: null,
        business: '',
        bank: null,
        bank_card_num: null,
        contract_prefix: null
      },
      cuRules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        status: [{
          required: true,
          message: '请选择是否启用',
          trigger: 'change'
        }],
        accounting: [{
          required: true,
          message: '清选择是否是独立核算部门',
          trigger: 'change'
        }],
        head: [{
          required: true,
          message: '请输入公司抬头',
          trigger: 'blur'
        }],
        bank: [{
          required: true,
          message: '请输入开户行',
          trigger: 'blur'
        }],
        bank_card_num: [{
          required: true,
          message: '请输入银行卡号',
          trigger: 'blur'
        }],
        contract_prefix: [{
          required: true,
          message: '请输入合同编号前缀',
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {},
  created() {
    this.getList()
  },
  mounted: function() {
  },
  methods: {
    // 新增弹出框
    showAdd(row = { id: 0, rid: 0 }) {
      const that = this
      that.dialogCU = true
      that.dialogCULoading = false
      that.resetForm()
      that.$refs['cuForm'] && this.$refs['cuForm'].resetFields()
      that.cuForm.pid = row.id
      that.cuForm.rid = row.rid
    },
    showEdit(row) {
      const that = this
      that.cuForm = Object.assign({}, row)
      that.dialogCU = true
      that.dialogCULoading = false
    },
    // 关闭弹窗
    dialogCUClose(formName) {
      const that = this
      switch (formName) {
        case 'cuForm':
          that.$refs['cuForm'].clearValidate()
          that.resetForm()
          break
      }
    },

    resetForm() {
      this.cuForm = {
        id: null,
        name: null,
        pid: 0,
        rid: 0,
        desp: null,
        status: 0,
        sort: 1,
        accounting: false,
        business: ''
      }
    },

    // 提交数据 增、改
    onSubmit(id) {
      // 表单校验
      this.$refs.cuForm.validate(valid => {
        // ~ 校验通过
        if (valid) {
          var obj = Object.assign({}, this.cuForm)

          // 显示loading
          this.dialogCULoading = true

          delete obj.created_at
          delete obj.updated_at
          delete obj.deleted_at

          // ~~ 修改
          if (id) {
            this.onEdit(obj)
          } else {
            // ~~ 添加
            delete obj.id
            this.onAdd(obj)
          }
        } else {
          // ~ 不通过
          return false
        }
      })
    },
    // 添加
    onAdd(obj) {
      return add(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },

    // 编辑
    onEdit(obj) {
      return edit(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },
    // 删除
    delVer(id = false) {
      this.$confirm('确认要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const ids = id ? [id] : this.selectIds
          del(ids).then(res => {
            const {
              code,
              date,
              message
            } = res
            this.getList()
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch()
    },
    // 是否启用
    changeStatus(status, row) {
      const flag = +!status
      this.$confirm('确认要' + (status ? '启用' : '禁用') + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const ids = [row.id]
          return change_status(ids, status).then(res => {
            const {
              message
            } = res
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch(() => {
        row.status = flag
      })
    },
    changeAccounting(accounting, row) {
      const flag = +!accounting
      this.$confirm('确认要' + (accounting ? '启用' : '禁用') + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const ids = [row.id]
          return change_accounting(ids, accounting).then(res => {
            const {
              message
            } = res
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch(() => {
        row.accounting = flag == 1
      })
    },
    // 获得table列表
    getList() {
      this.tabLoading = true
      console.log(this.listParams)
      return list(this.listParams)
        .then(res => {
          this.tableData = res.data
          this.tabLoading = false
        })
        .catch(() => {
          this.tabLoading = false
        })
    },

    // 重置搜索表单
    searchReset() {
      this.$refs.searchForm.resetFields()
      const params = this.$refs.searchForm.model
      this.listParams = Object.assign(this.listParams, params)
      this.getList()
    },
    // 搜索
    searchSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = this.$refs[formName].model
          if (!params.name) params.name = null
          this.listParams = Object.assign(this.listParams, params)
          this.getList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 表单多选
    handleSelectionChange(val) {
      this.selectIds = val.map(item => item.id)
    },
    // 带状态表格
    tableRowClassName({
      row
    }) {
      if (row.status === 0) {
        return 'stop-row'
      }
      return ''
    }
  }
}
</script>
<style scoped>
.search .el-form-item:last-child {
  margin-left: 35px;
}

.el-date-editor > .el-range-separator {
  width: 8% !important;
}

.operation button {
  padding: 8px;
}

.el-pagination {
  margin-top: 40px;
}
</style>
<style lang="scss" scoped>
.app-container {
  .el-table {
    margin-top: 20px;

    .stop-row {
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>
